import { getGCPackageContent, getOrgnList, getPlatPackageContent, getStudyPackageIncludes } from '@/api/Plan';
import { getOrgnParent } from '@/api/Plan/extra';
import Source from '@/components/SourceSelect/Entity/Source';
import { useAppSelector } from '@/redux/store';
import type { FormItemProps, TreeSelectProps } from 'antd';
import { TreeSelect } from 'antd';
import { groupBy, isEmpty } from 'lodash-es';
import { useEffect, useState } from 'react';
import { v4 as uuid } from 'uuid';
import { utils, type TreeNode } from 'ym-design';
import { CoursewareGroupToTypeObj, ECoursewareTypeToType, IStudyPackage } from './interface';

export const studyPlanTypeOptions = [
  {
    label: '周期循环',
    value: 'circle',
  },
  {
    label: '固定时间',
    value: 'fixed',
  },
];

// 循环--学习周期
export const circleTimeOptions = [
  {
    label: '1',
    value: 1,
  },
  {
    label: '2',
    value: 2,
  },
  {
    label: '3',
    value: 3,
  },
  {
    label: '5',
    value: 5,
  },
  {
    label: '7',
    value: 7,
  },
];

// 循环--学习时间
export const styleTimeOptions: () => { value: number; label: string }[] = () => {
  const options: { value: number; label: string }[] = [];
  for (let i = 0; i < 24; i++) {
    options.push({ value: i, label: i + '点' });
  }
  return options;
};

/**
 * @desc 学习时间下拉数据
 */
export const StudyHourOptions = new Array(24).fill(0).map((value, index) => {
  return {
    label: `${value + index}点`,
    value: value + index + '',
  };
});

/**
 * @desc 根据周期循环天数展示文案
 */
export function StudyTimeConcat(cycleTime?: number, hourStr?: string | number) {
  if (cycleTime && hourStr) {
    if (cycleTime === 1) {
      return `至次日${hourStr}点`;
    } else {
      return `至${cycleTime}日后${hourStr}点`;
    }
  } else {
    return null;
  }
}

type EntFlatData = {
  id: string;
  title: string;
  value: string;
  parentId: string;
};

type EntListTreeData = TreeNode<EntFlatData>[];
export function useEntListSelectTreeProps(options?: {
  ready?: boolean;
  onSuccess?(data: EntFlatData[], treeData: EntListTreeData): void;
}) {
  const { ready = true, onSuccess } = options ?? {};
  const [loading, setLoad] = useState(ready);
  const [treeData, setTreeData] = useState<EntListTreeData>();
  // const [treeData, setTreeData] = useState<any>();
  const { entId } = useAppSelector((state) => state.loginEnt); //organizationType 1:协会，0：企业

  useEffect(() => {
    if ((ready || !loading) && !treeData) {
      setLoad(true);
      getOrgnParent({ entId })
        .then((result) => {
          getOrgnList({ entId })
            .then((data) => {
              const arr = [...[{ entId: result.guid, name: result.name, parentId: '0' }], ...data];
              const _data = arr.map((v: any) => {
                return { id: v.entId, title: v.name, value: v.entId, parentId: v.parentId ?? result.guid };
              });
              const _treeData = utils.flat2Tree(_data, '0');
              setTreeData(_treeData);
              onSuccess?.(_data, _treeData);
            })
            .finally(() => {
              setLoad(false);
            });
        })
        .finally(() => {
          setLoad(false);
        });
    }
  }, [entId, ready]);

  return {
    fieldProps: {
      // 获取
      getValueFromEvent(values: string[] = [], titles: string[] = []) {
        // console.log('--获取-values---titles--extra--:', values, titles, extra);
        return values.map((value, index) => {
          return { entId: value, entName: titles[index] };
        });
      },
      // 回显，默认返回所有props
      getValueProps(value: { entId: string; entName: string }[] = []) {
        // console.log('--回显--value--:', value);
        return {
          value: value.map((v) => v.entId),
        };
      },
    } as FormItemProps,
    treeSelectProps: {
      treeData,
      disabled: loading,
      treeCheckable: true,
      placeholder: '请选择',
      maxTagCount: 2,
      showSearch: false,
      showCheckedStrategy: TreeSelect.SHOW_ALL,
      treeDefaultExpandAll: true,
      style: { width: 350 },
      maxTagTextLength: 6,
    } as TreeSelectProps,
  };
}

//获取类别 CategoryCascader 的父级value
export const getParentCode: (tree: any[], currCode: string) => string | undefined = (tree, currCode) => {
  for (let i = 0; i < tree.length; i++) {
    const { children, value } = tree[i];
    if (children && children.length > 0) {
      const currChildItem = children.find((childItem: any) => childItem.value == currCode);
      if (!isEmpty(currChildItem)) {
        return value;
      } else if (!isEmpty(children.children)) {
        const tempVal = getParentCode(children.children, currCode);
        if (!isEmpty(tempVal)) return tempVal;
      }
    }
  }
};

//注： 自建视频课件 新增提交的是videoList，详情返回的是vedioInfo,平台视频课件新增和详情返回的都是 vedioId ,新增学习计划时后端只接收videoList
// vedioId,vedioInfo 转换成 videoList
export const vedioIdOrVideoInfoTransformToVideoList: (item: any) => { hsVideoId: string; picUrl?: string }[] = (
  item,
) => {
  const { vedioId, videoList, vedioInfo } = item;
  if (!isEmpty(vedioId)) {
    return [{ hsVideoId: vedioId, picUrl: '' }];
  } else if (!isEmpty(videoList)) {
    return videoList;
  } else if (!isEmpty(vedioInfo)) {
    return JSON.parse(vedioInfo);
  }
};

// 新增学习计划时后端只接收picTextContent
//图文/pdf 课件 pictextContent 转成 picTextContent
export const pictextContentToPicTextContent: (item: any) => string = (item) => {
  const { picTextContent, pictextContent } = item;
  if (!isEmpty(picTextContent)) {
    return picTextContent;
  } else if (!isEmpty(pictextContent)) {
    return pictextContent;
  }
};

// 添加学习包
export const sourceModalChange: (
  values: Source[],
  menuActiveKey: string,
  sourceList: IStudyPackage[],
) => Promise<IStudyPackage[]> = (values, menuActiveKey, sourceList) => {
  return new Promise((resolve, reject) => {
    if (isEmpty(values)) {
      reject('请先选择学习包');
      return;
    }
    console.log('--handleSourceModalChange--values--menuActiveKey--:', values, menuActiveKey);
    //试卷,课件
    const combineId = values.map((item: Source) => item.id).join('_');
    const currSourceIndex = sourceList.findIndex((sourceItem: IStudyPackage) => sourceItem.id === combineId);
    if (currSourceIndex > -1) {
      reject(`学习包${currSourceIndex + 1}已存在`);
      return;
    }
    values.forEach((e) => {
      const packageType = menuActiveKey.includes('coursewarePackage') ? 'package' : 'courseware';
      const sourceType = e.from === 'government' ? '100' : '200'; // '100':企业协会自建 ，200：平台
      if (packageType === 'package') {
        const { id, from, name } = values[0];
        const currSourceIndex = sourceList.findIndex((sourceItem: IStudyPackage) => sourceItem.id === id);
        if (currSourceIndex > -1) {
          reject(`学习包${currSourceIndex + 1}已存在`);
          return;
        }
        const sourceOrigin = values[0].origin as any;
        const packageGuid = sourceOrigin.packageGuid || undefined;
        const isCharge = sourceOrigin.isCharge; // 1：收费，0：免费
        let request;
        if (sourceType === '100') {
          request = getGCPackageContent({ guid: id, pageNum: 1, pageSize: 9999 });
        } else {
          request = getPlatPackageContent({ relationId: id, relationType: 'package', pageNum: 1, pageSize: 9999 });
        }
        request
          .then((res: any) => {
            console.log('--AddFixedStudyPlan--getPlatPackageContent/getGCPackageContent--data--:', res);
            let studyList: any[] = [];
            if (sourceType === '100') {
              studyList = res.data.coursewareList.map((item: any) => ({
                ...item,
                videoList: vedioIdOrVideoInfoTransformToVideoList(item),
                picTextContent: pictextContentToPicTextContent(item),
                sourceGuid: id,
                sourceType,
                coursewareId: item.guid,
                // 自建课件包有type字段
              }));
            } else {
              studyList = res.data.list.map((item: any) => ({
                ...item,
                videoList: vedioIdOrVideoInfoTransformToVideoList(item),
                picTextContent: pictextContentToPicTextContent(item),
                type: ECoursewareTypeToType[item.coursewareType as keyof typeof ECoursewareTypeToType],
                sourceGuid: id,
                sourceType,
              }));
            }
            const finalValue: IStudyPackage = {
              id,
              packageType,
              sourceType,
              sourceGuid: packageGuid,
              isCharge,
              studyList,
            };
            sourceList.push(finalValue);
            resolve([...sourceList]);
            // form.setFieldValue('studyPackageList', [...sourceList]);
          })
          .catch((err) => {
            console.log('--AddFixedStudyPlan--getPlatPackageContent/getGCPackageContent--err--:', err);
            reject('AddFixedStudyPlan--getPlatPackageContent/getGCPackageContent--err');
          });
      } else {
        const tempPackageItem: IStudyPackage = {
          id: combineId,
          packageType,
          sourceType,
          isCharge: 0,
          studyList: [],
        };
        const isChargeIndex = values.findIndex((item: Source) => (item.origin as any).isCharge === 1); //付费
        if (isChargeIndex > -1) {
          tempPackageItem.isCharge = 1;
        }
        tempPackageItem.studyList = values.map((item: Source) => ({
          ...item,
          videoList: vedioIdOrVideoInfoTransformToVideoList(item.origin),
          picTextContent: pictextContentToPicTextContent(item.origin),
          type: (item.origin as any).type
            ? ECoursewareTypeToType[(item.origin as any).type as keyof typeof ECoursewareTypeToType]
            : CoursewareGroupToTypeObj[String((item.origin as any).coursewareGroup)],
          sourceType: item.from === 'government' ? '100' : '200',
          coursewareId: (item.origin as any).resourceId,
        }));
        sourceList.push(tempPackageItem);
        resolve([...sourceList]);
        // form.setFieldValue('studyPackageList', [...sourceList]);
      }
    });
  });
};

//计划模板进入添加页时，处理计划模板
export const dealWidthStudyTemplate = (guid: string, isCharge: number | undefined) => {
  return new Promise((resolve, reject) => {
    // 学习包
    //course：课程 package：包 learn：学习计划
    getStudyPackageIncludes({
      relationType: 'learn',
      relationId: guid,
      pageSize: 9999,
      pageNum: 1,
    })
      .then((res) => {
        console.log('--AddStudyPlan--getStudyPackageIncludes--res--:', res);
        const {
          code,
          data: { list },
        }: any = res;
        if (code === '200') {
          //排序 prevItem在左nextItem在右 -1 不交换顺序(从小到大) 1 交换顺序(从大到小)
          const sortList = list.sort((prevItem: any, nextItem: any) => prevItem.sortNum - nextItem.sortNum);
          //分组
          const newListMap = groupBy(sortList, 'sortNum');
          // console.log('--newListMap--:', newListMap);
          const studyPackageList = Object.keys(newListMap).map((key: string) => {
            const id = uuid();
            const packageIndex = newListMap[key].findIndex(
              (mapItem: any) => mapItem.coursewareType === 'vido' || 'pdf' || 'txt',
            );
            const packageType = packageIndex > -1 ? 'package' : 'courseware'; //学习计划模板只有课件包和试卷
            const sourceType = '200';
            const sourceGuid = packageType === 'package' ? guid : undefined;
            const studyList = newListMap[key].map((listItem: any) => ({
              ...listItem,
              videoList: vedioIdOrVideoInfoTransformToVideoList(listItem),
              picTextContent: pictextContentToPicTextContent(listItem),
              type: ECoursewareTypeToType[listItem.coursewareType as keyof typeof ECoursewareTypeToType],
              sourceGuid,
              sourceType,
            }));
            return {
              id,
              packageType,
              sourceType,
              sourceGuid,
              isCharge: isCharge || 0,
              studyList,
            };
          });
          resolve(studyPackageList);
        }
      })
      .catch((err) => {
        console.log('--getStudyPackageIncludes--err--:', err);
        reject(err);
      });
  });
};
